package org.penguin.study.bk.log.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.penguin.study.bk.base.query.QueryGenerator;
import org.penguin.study.bk.base.vo.Result;
import org.penguin.study.bk.log.entity.EventLog;
import org.penguin.study.bk.log.service.EventLogService;
import org.penguin.study.bk.base.util.NetWorkUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@Tag(name = "访问日志控制器", description = "访问日志")
@RestController
@RequestMapping("/event")
public class EventLogController {

    @Autowired
    private EventLogService eventLogService;

    /**
     * @return
     * @功能：新增
     */
    @Operation(summary = "访问日志表-新增访问日志", description = "访问日志表-新增访问日志")
    @PostMapping(value = "/add")
    public Result<EventLog> add(@RequestBody EventLog eventLog) {
        Result<EventLog> result = new Result<>();
        try {
            eventLog.setRequestTime(LocalDateTime.now());
            eventLog.setRequestIp(NetWorkUtil.getIp());
            eventLog.setOperatorId("e8e0e92c589bebdf3cad81c7f0b91dc5");
            eventLog.setOperatorFullName("系统管理员");
            eventLog.setCreatedBy("admin");
            eventLog.setResponseTime(LocalDateTime.now());
            eventLogService.save(eventLog);
            result.success("保存成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    @GetMapping(value = "/list")
    public Result<?> queryPageList(EventLog eventLog,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize",
            defaultValue = "10") Integer pageSize, HttpServletRequest request) {

        QueryWrapper<EventLog> queryWrapper = QueryGenerator.initQueryWrapper(eventLog, request.getParameterMap());
        Page<EventLog> page = new Page<>(pageNo, pageSize);
        IPage<EventLog> pageList = eventLogService.page(page, queryWrapper);
        return Result.ok(pageList);
    }
}
